<template>
  <div>
    <van-field
      v-model="sms"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button
          size="small"
          type="primary"
          @click="sendmsgcode"
          :disabled="flag2"
          ref="msg"
          >{{ txt }}</van-button
        >
      </template>
    </van-field>
<!-- -------------------------------------------------------------- -->
    <van-button
      class="but"
      type="danger"
      :disabled="!flag"
      round
      block
      @click="nextreg3"
      >下一步</van-button
    >
  </div>
</template>

<script>
import { doEndMsgCode } from "../../api/user";
import { doCheckCode } from "../../api/user";
import Vue from "vue";
import { Dialog } from "vant";
Vue.use(Dialog);
export default {
  data() {
    return {
      sms: "",
      flag2: false,
      count: 60,
      timer: null,
      txt: "发送验证码",
    };
  },
  computed: {
    flag() {
      return /^\d{5}$/.test(this.sms);
    },
  },
  methods: {
    sendmsgcode() {
      //点击发送验证码,并且加入定时器，用到ref知识点，也可以用{{txt}}换掉文字然后操作属性
      doEndMsgCode({ tel: JSON.parse(localStorage.getItem("tel")) }).then(
        (data) => {
          console.log(JSON.parse(localStorage.getItem("tel")));
          console.log(data);
          console.log(data.data.data);
          this.sms = data.data.data;
        }
      );

      this.timer = setInterval(() => {
        //定时器，倒计时点击后60s内不能点击
        this.flag2 = true; //不能点击
        this.txt = this.count-- + "s后重新发送"; //文本改变
        if (this.count <= 0) {
          //倒计时结束，清除定时器
          this.txt = "重新发送验证码"; //文本改变
          this.flag2 = false; //可以点击
          this.count = 60; //count恢复成60s
          clearInterval(this.timer);
        }
      }, 1000);
    },
    nextreg3() {
      doCheckCode({
        tel: JSON.parse(localStorage.getItem("tel")),
        telcode: this.sms,
      }).then((data) => {
        console.log(JSON.parse(localStorage.getItem("tel")));
        console.log(data);
        if (data.data.code == "10007") {
          //已经注册过
          Dialog.confirm({
            //引入vant
            message: "验证码错误",
          })
            .then(() => {
              this.sms = "";
            })
            .catch(() => {
              // on cancel
            });
        } else if (data.data.code == "200") {
          // 验证码正确
          this.$router.push("/register/reg3");
        }
      });
    },
  },
};
</script>

<style scoped>
.but {
  width: 80%;
  margin: 1rem auto;
}
</style>